package com.yylending.las.main;

import android.text.TextUtils;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by ying_he on 2017/9/5.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public class InviteCodeVerifyPresenter extends Presenter<InviteCodeVerifyModel, InviteCodeVerifyPresenter.View> {

	private View mView;
	public static final int FUNCTION_GET_INVITE_CODE_STATUS = 1001;
	public static final int FUNCTION_SUBMIT_INVITE_CODE_STATUS = 1002;
	private static final String THE_USER_NEVER_BIND_CHANNEL = "100018"; // 用户未绑定渠道
	private static final String ERROR_TIPS = "服务器繁忙，请稍后再试";

	public static class Generator implements PresenterFactory<InviteCodeVerifyPresenter> {
		@Override
		public InviteCodeVerifyPresenter create() {
			return new InviteCodeVerifyPresenter();
		}
	}

	@Override
	public void attach(InviteCodeVerifyPresenter.View view) {
		mView = view;
		mModel = new InviteCodeVerifyModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public interface View extends IView {
		void submitInviteCodeSuccess();
		void submitInviteCodeFailed();

		void getInviteCodeStatusSuccess(boolean hasInviteCode);
		void getInviteCodeStatusFailed(String tips);
	}

	public void getInviteCodeStatus() {
		execute(null, FUNCTION_GET_INVITE_CODE_STATUS, true);
	}

	public void submitInviteCode(String inviteCode){
		InviteCodeVerifyModel.SubmitInviteCodeParams params = new InviteCodeVerifyModel.SubmitInviteCodeParams();
		params.inviteCode = inviteCode;
		execute(params, FUNCTION_SUBMIT_INVITE_CODE_STATUS, true);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void getInviteCodeStatusResult(InviteCodeVerifyModel.GetInviteCodeStatusResult result) {
		if (result != null){
			if (BaseResultEntity.isResponseSuccess(result)){
				mView.getInviteCodeStatusSuccess(true);
				return;
			}else if (TextUtils.equals(THE_USER_NEVER_BIND_CHANNEL, result.getRetCode())){
				mView.getInviteCodeStatusSuccess(false);
				return;
			}
		}
		mView.getInviteCodeStatusFailed(ERROR_TIPS);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void submitInviteCodeStatusResult(InviteCodeVerifyModel.SubmitInviteCodeResult result) {
		if (result != null){
			if (BaseResultEntity.isResponseSuccess(result)){
				mView.submitInviteCodeSuccess();
			}else{
				mView.submitInviteCodeFailed();
			}
		}
	}
}